package cn.cinz.util;

import cn.cinz.pojo.Code;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Random;
import java.util.UUID;


/**
 * 发送短信验证码util类
 */
public class SendSmsUtil {

    private static String code = "";//验证码

    public static String getSendSms(String userPhone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tN1g5dnETVjuMowHAys", "tsNIsobZMJjOJvRnyFyIa52HayKXAD");//accessKey签名
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", userPhone);//手机号
        request.putQueryParameter("SignName", "成易学习");//短信签名
        request.putQueryParameter("TemplateCode", "SMS_219743070");//短信模板code
        request.putQueryParameter("TemplateParam", code = getSmsVerificationCode());
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());//日志打印
        } catch (
                ServerException e) {
            e.printStackTrace();
        } catch (
                ClientException e) {
            e.printStackTrace();
        }
        return code;
    }

    /**
     * 生成六位随机短信验证码
     * @return 验证码
     */
    private static String getSmsVerificationCode() {

        //解决第二次发送验证码时，code不为空，为redis中存入值的情况
        if (code != "" && code != null){
            code = "";
        }

        if (code == null || code == ""){
            Random random = new Random();
            for (int i = 0; i < 6; i++){
                int rand = random.nextInt(10);
                code += rand;
            }
        }

        code = String.valueOf(new Code(code));//Code的toString实现字符串拼接
        return code;
    }

}
